<template>
  <div class="login-container">
    <h2>管理员登录</h2>
    <input v-model="email" type="email" placeholder="用户名" @keyup.enter="login">
    <input v-model="password" type="password" placeholder="密码" @keyup.enter="login">
    <button @click="login">登录</button>
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
  </div>
</template>

<script>
import jq from "jquery"

export default {
  name: 'LoginView',
  data() {
    return {
      email: '',
      password: '',
      errorMessage: ''
    };
  },
  methods: {
    login() {
      // 清除旧错误信息
      this.errorMessage = ''

      // 前端基础验证
      if (!this.email || !this.password) {
        this.errorMessage = '请输入邮箱和密码'
        return
      }

      const _this = this
      jq.ajax({
        type: "GET",
        url: "http://127.0.0.1:3000/admission",
        success(res) {
          if (res.data && Array.isArray(res.data)) {
            console.log('res.data', res.data)
            const validUser = res.data.find(u =>
              u.Email === _this.email &&
              u.PassWord === _this.password
            );

            if (validUser) {
              localStorage.setItem('isLoggedIn', 'true');
              localStorage.setItem('username', validUser.Name); // 存储用户名
              localStorage.setItem('email', validUser.Email); // 存储邮箱用于后续查询
              _this.$router.replace('/dash/sale')
            }
          }
        },
        error() {
          _this.errorMessage = '服务器连接失败，请稍后重试'
        }
      });
    }
  }
};
</script>

<style scoped>
.login-container {
  max-width: 300px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: center;
}

input {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #0056b3;
}

.error-message {
  color: #dc3545;
  margin-top: 10px;
  font-size: 0.9em;
}
</style>